const express = require('express');
const router = express.Router();
const Carousel = require('../models/Carousel');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');

const currentDir = __dirname;
const targetDir = path.join(currentDir, 'Carousel');

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, targetDir); // 上传的文件将保存在public/Carousel文件夹下
    },
    filename: (req, file, cb) => {
        // 使用哈希值作为文件名，以确保唯一性
        const ext = path.extname(file.originalname);
        const hash = crypto.randomBytes(16).toString('hex');
        cb(null, `${hash}${ext}`);
    },
});
const upload = multer({ storage });
// 获取所有轮播图
router.get('/getAllCarousels', (req, res) => {
    try {
        Carousel.find()
            .then(carousels => {
                res.status(200).json({ success: true, data: carousels });
            })
            .catch(err => {
                console.error(err);
                res.status(500).json({ success: false, message: 'Internal Server Error' });
            });
    } catch (error) {
        console.log(error);
    }
});

router.post('/addCarousel', upload.single('image'), (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ message: 'No file uploaded' });
        }
        // 获取本地域名，此处假设您的应用运行在 http://localhost:3000
        const localDomain = 'https://2g59l88703.imdo.co';
        // 构建完整的图片URL
        const imageUrl = `${localDomain}/${req.file.filename}`;
        const { title } = req.body;
        const carousel = new Carousel({
            title,
            images: [{ imageUrl }], // 将图片URL添加到轮播图数组中
        });
        carousel.save()
            .then(result => {
                res.status(201).json({ imageUrl }); // 返回图片URL
            })
            .catch(err => {
                console.error(err);
                res.status(500).json({ message: 'Internal Server Error' });
            });
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Internal Server Error' });
    }
})


module.exports = router;